package com.ruoyi.web.controller.system;

import java.util.Iterator;
import java.util.List;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.domain.entity.ChannelSort;
import com.ruoyi.system.service.IChannelSortService;

/**
 * 渠道分类Controller
 * 
 * @author yanghuiliao
 * @date 2022-11-29
 */
@RestController
@RequestMapping("/system/sort")
public class ChannelSortController extends BaseController
{
    @Autowired
    private IChannelSortService channelSortService;

    /**
     * 获取部门列表
     */
    @PreAuthorize("@ss.hasPermi('system:sort:list')")
    @GetMapping("/list")
    public AjaxResult list(ChannelSort channelSort)
    {
        List<ChannelSort> channelSorts = channelSortService.selectChannelSortList(channelSort);
        return AjaxResult.success(channelSorts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:sort:list')")
    @GetMapping("/list/exclude/{id}")
    public AjaxResult excludeChild(@PathVariable(value = "id", required = false) Long id)
    {
        List<ChannelSort> channelSorts = channelSortService.selectChannelSortList(new ChannelSort());
        Iterator<ChannelSort> it = channelSorts.iterator();
        while (it.hasNext())
        {
            ChannelSort d = (ChannelSort) it.next();
            if (d.getId().intValue() == id
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), id + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(channelSorts);
    }

    /**
     * 获取第二级菜单
     * @param channelSort
     * @return
     */
    @GetMapping("/list/secondChild")
    public AjaxResult secondChild(ChannelSort channelSort)
    {
        List<ChannelSort> channelSorts = channelSortService.selectChannelSortList(new ChannelSort());

        return AjaxResult.success(channelSorts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:sort:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id)
    {
        return AjaxResult.success(channelSortService.selectChannelSortById(id));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(ChannelSort channelSort)
    {
        List<ChannelSort> channelSorts = channelSortService.selectChannelSortList(channelSort);
        return AjaxResult.success(channelSortService.buildDeptTreeSelect(channelSorts));
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<ChannelSort> channelSorts = channelSortService.selectChannelSortList(new ChannelSort());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", null);
        ajax.put("depts", channelSortService.buildDeptTreeSelect(channelSorts));
        return ajax;
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:sort:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody ChannelSort channelSort)
    {
        if (UserConstants.NOT_UNIQUE.equals(channelSortService.checkChannelSortUnique(channelSort)))
        {
            return AjaxResult.error("新增分类'" + channelSort.getName() + "'失败，分类名称已存在");
        }
        channelSort.setCreateBy(SecurityUtils.getUsername());
        return toAjax(channelSortService.insertChannelSort(channelSort));
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('system:sort:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody ChannelSort channelSort)
    {
        if (UserConstants.NOT_UNIQUE.equals(channelSortService.checkChannelSortUnique(channelSort)))
        {
            return AjaxResult.error("修改部门'" + channelSort.getName() + "'失败，部门名称已存在");
        }
        else if (channelSort.getParentId().equals(channelSort.getId()))
        {
            return AjaxResult.error("修改部门'" + channelSort.getName() + "'失败，上级部门不能是自己");
        }

        channelSort.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(channelSortService.updateChannelSort(channelSort));
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('system:sort:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id)
    {
        if (channelSortService.hasChildByDeptId(id))
        {
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        if (channelSortService.checkDeptExistUser(id))
        {
            return AjaxResult.error("部门存在用户,不允许删除");
        }
        return toAjax(channelSortService.deleteChannelSortById(id));
    }
}
